<?php
/**
 * 小蜗牛留言本
 * 本文件内代码属于“小蜗牛留言本”项目，禁止修改再发布本程序源码，禁止去除页面底部的版权申明。所有版权保留
 * User: upliu
 * Email: 753073861@qq.com
 * QQ: 753073861
 * 程序主页：http://demo.upliu.net/snail-guestbook/
 */

require __DIR__ . '/../init.php';

check_login();

if (!is_current_login_user_super_admin()) {
    die('Pemission denied!');
}

$action = !empty($_GET['action']) ? $_GET['action'] : 'list';

switch ($action) {
    case 'list':
        $users = get_user_list();
        echo renderWithAdminLayout('admin/user', array(
            'users' => $users,
        ));
        exit();
        break;
    case 'set-active':
        set_admin_user_active($_GET['user_id']);
        set_success_message('已启用用户');
        break;
    case 'set-forbidden':
        set_admin_user_forbidden($_GET['user_id']);
        set_success_message('已禁用用户');
        break;
    case 'set-password';
        change_admin_user_password($_POST['user_id'], $_POST['password']);
        break;
    case 'delete':
        delete_admin_user_by_id($_GET['user_id']);
        set_success_message('删除成功');
        break;
    case 'add':
        if (empty($_POST)) {
            echo renderWithAdminLayout('admin/user_add');
            exit();
        } else {
            if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['dept_id'])) {
                try {
                    add_admin_user($_POST['username'], $_POST['password'], (int)$_POST['dept_id']);
                    set_success_message('用户添加成功');
                } catch (\Exception $e) {
                    set_error_message($e->getMessage());
                    echo renderWithAdminLayout('admin/user_add', array(
                        'user' => $_POST,
                    ));
                    exit();
                }
            } else {
                set_error_message('提交数据不完整');
                echo renderWithAdminLayout('admin/user_add', array(
                    'user' => $_POST,
                ));
                exit();
            }
        }
        break;
    case 'update':
        $user_id = $_GET['user_id'];
        if (empty($_POST)) {
            $user = get_user_info($user_id);
            echo renderWithAdminLayout('admin/user_update', array(
                'user' => $user,
                'is_update_user' => true,
            ));
            exit();
        } else {
            change_admin_user_info($user_id, $_POST);
            set_success_message('更新用户信息成功');
        }
        break;
}

redirect_path('admin/user.php');